var ws;//websocket实例
var lockReconnect = false;//避免重复连接
function createWebSocket(url) {
    try {
        ws = new WebSocket(url);
        initEventHandle();
        return true;
    } catch (e) {
        reconnect(url);
    }
    return false;
}

function initEventHandle() {
    ws.onclose = function () {
        $("#textArea").append("<li>断开连接</li>");
        reconnect(wsUrl);
    };
    ws.onerror = function () {
        reconnect(wsUrl);
    };
    ws.onopen = function () {
        //心跳检测重置
        $.alert("登录成功", 1);
        lockReconnect = true;
        heartCheck.reset().start();
        var msg = new MessageModel();
        msg.setUserAccount(gUserInfo.userAccount)
            .setUserIcon(gUserInfo.userIcon)
            .setType("login");
        ws.send(JSON.stringify(msg));
    };
    //所有后台放回数据由这里接受  唯一入口
    ws.onmessage = function (event) {
        var data = JSON.parse(event.data);
        if (currentWindow == "list") {
            if (data.type == "group" || data.type == "p2p")
                $(".chat_window").addClass("new");
        }
        if (!(data.type == "connect" || data.type == "heartbeat")) {
            if (data.type == "group")
                sendMessageToUser("group", data);
            else if (data.type == "p2p")
                sendMessageToUser(data.userAccount, data);
            else if (data.type == "login")
                userLoginAction(data);
        }
        //如果获取到消息，心跳检测重置
        heartCheck.reset().start();
    }
}

function reconnect(url) {
    if (lockReconnect) return;
    lockReconnect = true;
    //没连接上会一直重连，设置延迟避免请求过多
    setTimeout(function () {
        createWebSocket(url);
        lockReconnect = false;
    }, 2000);
}


//心跳检测
var heartCheck = {
    timeout: 60000,//60秒
    timeoutObj: null,
    serverTimeoutObj: null,
    reset: function () {
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        return this;
    },
    start: function () {
        var self = this;
        this.timeoutObj = setTimeout(function () {
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常
            var sendMessage = new MessageModel().setType("heartBeat");
            ws.send(JSON.stringify(sendMessage));
            self.serverTimeoutObj = setTimeout(function () {//如果超过一定时间还没重置，说明后端主动断开了
                ws.close();//如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            }, self.timeout)
        }, this.timeout)
    }
};

function sendMessageToUser(userAccount, jsonData) {
    if (jsonData.userAccount == gUserInfo.userAccount) return null;
    if (!windowList[userAccount]) {
        jsonData.userNickname = jsonData.userNickName;
        windowList[userAccount] = [];
        windowList[userAccount + "Count"] = 0;
        windowList.chatWindow.push(jsonData);
    }
    windowList[userAccount].push(jsonData);
    if (currentWindow == "chat") {
        if (!$("#" + userAccount + "")[0]) {
            jsonData.userNickname = jsonData.userNickName;
            $.showChatList(jsonData, false);
        }
    }
    if (currentUser == userAccount)
        $.sendMsg(jsonData.userIcon, jsonData.content, "left");
    else {
        windowList[userAccount + "Count"] += 1;
        var $windows = $("#" + userAccount + "");
        $windows.find(".message_count").html(windowList[userAccount + "Count"]);
        $windows.find(".message_bubble").show();
    }
}

/*****************上下线 设置*********************/
function userLoginAction(userInfo) {
    if (userInfo.type == "login")
        var $onlineUser = $("#" + userInfo.userAccount + "").removeClass("out");

}
